﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HF.WorkFlow.Template;
using HF.WorkFlow.Engine;
using eWorld.UI;
using HF.Framework;
using HF.BaseWebCtrlLib;
using System.Threading;
using System.IO;
using System.Drawing;
using HF.Framework.Log;
using HF.WorkFlow.Const;
using HF.Framework.Web;
using HF.Forms.Data;
using HF.WorkFlow.DataContract;
public partial class BasePages_WorkTaskCtrlPage : System.Web.UI.Page
{
    string UserId = "";
    string WorkflowId = "";
    string WorktaskId = "";
    string WorkflowInsId = "";
    string WorktaskInsId = "";
    string OperatorInsId = "";
    string pageState = "";//新建,修改,查看
    string OperStatus = "";//操作状态,0 未处理未认领，1处理完成，2指派他人，3认领未处理
    ArrayList UserCtrlList = new ArrayList();//控件列表
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
                BaseUserPage.LoadWaitPage();//必须加在 这里，否则打印时出现正在加载对话框

            UserId = this.Page.User.Identity.Name;
            InitData();
            
        }
        catch (Exception ex)
        {
            LogData.WriteLog("平台打开处理界面错误:" + ex, WorkflowInsId);
            throw ex;
        }
        finally
        {
            if (!IsPostBack)
                BaseUserPage.FreeWaitPage();
        }
       
        
    }
    
    private void InitData()
    {
         if (Request["state"] != null)
         {
             pageState = Request["state"].ToString();
         }
        if (Request["OperatorInstanceId"] != null)
        {
            OperatorInsId = Request["OperatorInstanceId"].ToString();
            DataTable dt = OperatorInstance.GetInstance().GetOperatorInstanceView(OperatorInsId);
            if (dt != null && dt.Rows.Count > 0)
            {
                WorkflowId = dt.Rows[0]["WorkflowId"].ToString(); 
                WorktaskId = dt.Rows[0]["WorktaskId"].ToString(); 
                WorkflowInsId = dt.Rows[0]["WorkFlowInstanceId"].ToString(); 
                WorktaskInsId = dt.Rows[0]["WorkTaskInstanceId"].ToString(); 
                lbFlowInsCaption.Text = dt.Rows[0]["FlowInstanceCaption"].ToString();
                lbFlowNo.Text = dt.Rows[0]["workflowNo"].ToString();
                lbWorkflowDes.Text = dt.Rows[0]["Description"].ToString();
                lbTaskCaption.Text = dt.Rows[0]["TaskInstanceCaption"].ToString();
                lbTitle.Text = lbTaskCaption.Text;
                lbUser.Text = dt.Rows[0]["pOperatedDes"].ToString();
                lbTime.Text = dt.Rows[0]["taskStartTime"].ToString();
                if (dt.Rows[0]["Priority"].ToString().Length>0)
                drpPriority.SelectedIndex=Convert.ToInt16( dt.Rows[0]["Priority"])-1;
                OperStatus = dt.Rows[0]["OperStatus"].ToString();

                //绑定流程历史
                //GetWorkflowHistory(WorkflowInsId);


                DataTable cdt = MainChildForm.GetInstance().GetWorkTaskFormsView(WorktaskId);
                string ctrlPath = "";
                string ctrlState = "";
                string ctrlID = "";
                foreach (DataRow dr in cdt.Rows)
                {
                    CollapsablePanel panel = new CollapsablePanel();
                    panel.CollapseImageUrl = "../Images/collapse.gif";
                    panel.ExpandImageUrl = "../Images/expand.gif";
                    panel.ExpandText = "展开";
                    panel.CollapseText = "关闭";
                    panel.Visible = true;
                    
                    panel.ExpandText = dr["ChildCaption"].ToString();
                    ctrlState = dr["FormState"].ToString();
                    ctrlPath = dr["FilePath"].ToString();
                    ctrlID = dr["FileName"].ToString();
                    string filename =Server.MapPath( @"..\" + ctrlPath);//用户控件文件名
                    if (File.Exists(filename))
                    {
                        BaseUserControl c = (BaseUserControl)this.LoadControl(@"..\" + ctrlPath);
                        c.WorkflowId = WorkflowId;
                        c.PageState = pageState;
                        c.ID = ctrlID;//指定id便于取界面元素
                        if (pageState == WorkFlowConst.STATE_VIEW)//如果全页只读，每个usercontrol的ctrlSate失效
                            c.CtrlState = WorkFlowConst.STATE_VIEW;
                        else
                        c.CtrlState = ctrlState;
                        c.WorkflowInsId = WorkflowInsId;
                        c.WorktaskId = WorktaskId;
                        c.WorktaskInsId = WorktaskInsId;
                        c.OperatorInsId = OperatorInsId;
                        c.InitUserControl();//执行控件的初始化事件
                        UserCtrlList.Add(c);//加到用户控件列表中
                        panel.Controls.Add(c);
                    }
                    else
                    {
                        Label l = new Label();
                        l.ForeColor =Color.Red ;
                        l.Text = filename+"表单文件不存在或者没有配置表单,无法加载表单!";
                        panel.Controls.Add(l);
 
                    }
                    ctrlPlace.Controls.Add(panel);
                }
            }
            
            generalCmdButton();//常用的按钮
            powerButton();//根据控制权限创建的按钮
            printButton();//打印的按钮
            
            
        }
    }
    //private void  GetWorkflowHistory(string workFlowInsId)
    //{
    //    DataTable dt = WorkFlowInstance.GetInstance().GetWorkFlowHistory(workFlowInsId);
    //    gvHistory.DataSource = dt;
    //    gvHistory.DataBind();
    //}
    /// <summary>
    /// 保存表单业务数据
    /// </summary>
    private bool SaveUserControl(bool IsDraft)
    {
        try
        {
            if (pageState == WorkFlowConst.STATE_VIEW) return true;
            foreach (BaseUserControl bc in UserCtrlList)
            {
                if (bc.CtrlState == WorkFlowConst.STATE_VIEW) continue;
                bc.SaveUserControl(IsDraft);
            }
            return true;
        }
        catch
        {
            throw;
        }
    }
    #region 动态加载任务命令按钮,退回,指派，动态指定下一任务处理人按钮
    /// <summary>
    /// 根据权限加载 退回,指派，动态指定下一任务处理人按钮
    /// </summary>
    private void powerButton()
    {
        string powerStr = "";
        DataTable dt = WorkTaskPower.GetInstance().GetTaskPowers(WorktaskId); 
        foreach (DataRow dr in dt.Rows)
        {
            powerStr =powerStr+ dr["PowerName"].ToString()+","; 
        }
        if (powerStr.IndexOf(WorkFlowConst.WorkTask_Return) > -1)//允许退回
        {
            Button btnCommand = new Button();
            btnCommand.Text = "退回";
            btnCommand.Click += new EventHandler(taskBackButtonEvent);
            btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
            cmdBtnPlace.Controls.Add(btnCommand);
            Literal lab1 = new Literal();
            lab1.Text = "&nbsp;&nbsp;";
            cmdBtnPlace.Controls.Add(lab1);
        }
        if (powerStr.IndexOf(WorkFlowConst.WorkTask_Assign) > -1)//允许指派
        {
            Button btnCommand = new Button();
            btnCommand.Text = "指派";
            btnCommand.Click += new EventHandler(taskAssignButtonEvent);
            btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
            cmdBtnPlace.Controls.Add(btnCommand);
            Literal lab1 = new Literal();
            lab1.Text = "&nbsp;&nbsp;";
            cmdBtnPlace.Controls.Add(lab1);
        }
        if (powerStr.IndexOf(WorkFlowConst.WorkTask_DyAssignNext) > -1)//允许动态指定下一步处理人
        {
            BaseUserControl c = (BaseUserControl)this.LoadControl(@"..\BaseUserControls\DyAssignNext.ascx");
            c.WorkflowId = WorkflowId;
            c.ID = "nextCtrl";//必须指定名称。js代码才能取到
            c.PageState = pageState;
            c.CtrlState = WorkFlowConst.STATE_MOD;
            c.WorkflowInsId = WorkflowInsId;
            c.WorktaskId = WorktaskId;
            c.WorktaskInsId = WorktaskInsId;
            c.OperatorInsId = OperatorInsId;
            c.InitUserControl();//执行控件的初始化事件
            UserCtrlList.Add(c);//加到用户控件列表中
            DyAssignPlace.Controls.Add(c);
            
        }
        initButton();//流程按钮


    }
    /// <summary>
    /// 根据任务配置加载流程命令按钮
    /// </summary>
    private void initButton()
    {
        DataTable taskCommand =WorkTaskCommand.GetInstance().GetTaskCommands(WorktaskId);
        foreach (DataRow dr in taskCommand.Rows)
        {
            string cmdName = dr["CommandName"].ToString();
            Button btnCommand = new Button();
            btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
            btnCommand.Text = cmdName;
            btnCommand.Click += new EventHandler(runButtonEvent);
            cmdBtnPlace.Controls.Add(btnCommand);
            Literal lab1 = new Literal();
            lab1.Text = "&nbsp;&nbsp;";
            cmdBtnPlace.Controls.Add(lab1);
        }
    }
    /// <summary>
    /// 提交流程事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void runButtonEvent(object sender, EventArgs e)
    {

        if (SaveUserControl(false))
        {
            string command = (sender as Button).Text;

            WorkTaskInstanceNextOperEntity entity = new WorkTaskInstanceNextOperEntity();
            WorkTaskInstanceNextOper worktaskNexOper = new WorkTaskInstanceNextOper();
            entity.NextOperId = Guid.NewGuid().ToString();
            entity.UserId = "hxx";
            entity.UserName = "";
            entity.WorkFlowId = WorkflowId;
            entity.WorkTaskId = WorktaskId;
            entity.WorkFlowInstanceId = WorkflowInsId;
            entity.WorkTaskInstanceId = WorktaskInsId;
            entity.Status = "0";
            worktaskNexOper.NextOperInsert(entity);


            WorkFlowRuntime wfruntime = new WorkFlowRuntime();
            wfruntime.RunSuccess += new WorkFlowRuntime.RunSuccessEventHandler(wfruntime_RunSuccess);
            wfruntime.RunFail += new WorkFlowRuntime.RunFailEventHandler(wfruntime_RunFail);
            wfruntime.Run(UserId, OperatorInsId, command);
            Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
        }
        else
        {
            throw new Exception("保存业务数据失败，流程无法提交!!");
        }
    }
    private void wfruntime_RunSuccess(object sender, WorkFlowEventArgs e)
    {
 
    }
    private void wfruntime_RunFail(object sender, WorkFlowEventArgs e)
    {
 
    }
    /// <summary>
    /// 任务退回事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void taskBackButtonEvent(object sender, EventArgs e)
    {
        WorkFlowRuntime wfruntime = new WorkFlowRuntime();
        //wfruntime.TaskBack(UserId, OperatorInsId);
        wfruntime.TaskBackApplicant(UserId, OperatorInsId);
        Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
    }


    /// <summary>
    /// 任务指派事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void taskAssignButtonEvent(object sender, EventArgs e)
    {

        string dlg = "window.open( 'AssignTask.aspx?OperatorInstanceId=" + OperatorInsId + "','newwindow'," +
       " 'height=200,width=650,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no')";
        if (!this.IsStartupScriptRegistered(UserId))
            this.RegisterStartupScript(UserId, "<script>" + dlg + "</script>");


    }
    #endregion


    #region 常用按钮,认领,草稿,放弃

    /// <summary>
    /// 常用按钮,认领,草稿,放弃
    /// </summary>
    private void generalCmdButton()
    {
       
        Button btnCommand = new Button();
        btnCommand.Text = "认领";
        btnCommand.Click += new EventHandler(claimButtonEvent);
        btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus=="0");
        cmdBtnPlace.Controls.Add(btnCommand);
        Literal lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        cmdBtnPlace.Controls.Add(lab1);

        btnCommand = new Button();
        btnCommand.Text = "草稿";
        btnCommand.Click += new EventHandler(saveButtonEvent);
        btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus!="0");
        cmdBtnPlace.Controls.Add(btnCommand);
         lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        cmdBtnPlace.Controls.Add(lab1);

        btnCommand = new Button();
        btnCommand.Text = "放弃";
        btnCommand.Click += new EventHandler(taskAbnegateButtonEvent);
        btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
        cmdBtnPlace.Controls.Add(btnCommand);
        lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        cmdBtnPlace.Controls.Add(lab1);
       
    }
    /// <summary>
    /// 草稿
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void saveButtonEvent(object sender, EventArgs e)
    {
        if (SaveUserControl(true))
            WorkDialog.ShowMessage(this, "保存草稿成功。");
    }
    /// <summary>
    /// 任务放弃认领
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void taskAbnegateButtonEvent(object sender, EventArgs e)
    {

        WorkFlowRuntime wfruntime = new WorkFlowRuntime();
        wfruntime.TaskUnClaim(UserId, OperatorInsId);
        Response.Redirect(Request.RawUrl);//刷新页面
    }
    /// <summary>
    /// 认领任务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void claimButtonEvent(object sender, EventArgs e)
    {
        WorkFlowRuntime wfruntime = new WorkFlowRuntime();
        wfruntime.TaskClaim(UserId, OperatorInsId);
        Response.Redirect(Request.RawUrl);//刷新页面
    }
    #endregion


    #region 打印等网页按钮
    /// <summary>
    /// 打印按钮
    /// </summary>
    private void printButton()
    {
        Button btnCommand = new Button();
        btnCommand.Text = "打印本表单";
        btnCommand.Click += new EventHandler(PrintClicked);
        generalPlace.Controls.Add(btnCommand);
        Literal lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);

        btnCommand = new Button();
        btnCommand.Text = "直接打印本表单";
        btnCommand.Click += new EventHandler(PrintPageClicked);
        generalPlace.Controls.Add(btnCommand);
        lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);

        btnCommand = new Button();
        btnCommand.Text = "打印设置";
        btnCommand.Click += new EventHandler(PageSetupClicked);
        generalPlace.Controls.Add(btnCommand);
        lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);

        btnCommand = new Button();
        btnCommand.Text = "打印预览";
        btnCommand.Click += new EventHandler(PreviewClicked);
        generalPlace.Controls.Add(btnCommand);
        lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);
    }
    /// <summary>
    /// 打印本表单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PrintClicked(object sender, EventArgs e)
    {

        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(6,1);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }

    /// <summary>
    /// 直接打印本表单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PrintPageClicked(object sender, EventArgs e)
    {

        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(6,6);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }

    /// <summary>
    /// 打印设置
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PageSetupClicked(object sender, EventArgs e)
    {

        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(8,1);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }

    /// <summary>
    /// 打印预览
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PreviewClicked(object sender, EventArgs e)
    {

        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(7,1);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }
    #endregion
    ///// <summary>
    ///// 等待数据加载时操作
    ///// </summary>
    //private void loadplan()
    //{
    //    string loadtext = "正在加载页面，请您耐心等待";
    //    Response.Write("<div id='mydiv' width='400px'  style='left:40% ;POSITION: absolute;TOP: 50px;height:150px;background-image:url(../Resources/image/load.gif);background-repeat: no-repeat; background-position: bottom'>");
    //    Response.Write("_");
    //    Response.Write("</div>");
    //    Response.Write("<script>var mydiv= document.getElementById(\"mydiv\");mydiv.innerText = '';</script>");
    //    Response.Write("<script language=javascript>");
    //    Response.Write("var output = '" + loadtext + "';");
    //    Response.Write("var dots = 0;var dotmax = 10;function ShowWait()");
    //    Response.Write("{dots++;if(dots>=dotmax)dots=1;");
    //    Response.Write("mydiv.innerText = output;}");
    //    Response.Write("function StartShowWait(){mydiv.style.visibility = 'visible'; window.setInterval('ShowWait()',1000);}");
    //    Response.Write("function HideWait(){mydiv.style.visibility = 'hidden';mydiv.style.display='none';window.clearInterval();}");
    //    Response.Write("StartShowWait();</script>");
    //    Response.Flush();
    //    Thread.Sleep(10);
    //} 
}
